require 'rubygems'
gem "rspec", "<=1.2.9"
require 'selenium/rake/tasks'
require 'spec/rake/spectask'
require 'fileutils'
require 'yaml'
require "net/http"
require "ruby2jar"



require File.dirname(__FILE__) + '/grid/ruby/tcp_socket_extensions'
require File.dirname(__FILE__) + '/grid/ruby/file_extensions'
require File.dirname(__FILE__) + '/grid/ruby/java/classpath'
require File.dirname(__FILE__) + '/grid/ruby/java/vm'
require File.dirname(__FILE__) + '/grid/ruby/s_grid/hub'
require File.dirname(__FILE__) + '/grid/ruby/s_grid/remote_control'
require 'rake/gempackagetask'

#require File.join(File.dirname(__FILE__), "lib", "ruby2jar")


desc "Print help"
task :help do
  puts <<-EOS

******************** Running tests on Selenium RC ***************************

Selenium server startup
------------------------------------------------------------------------------------
rake rc:restart                         # Restart Selenium Remote Control
rake rc:start                           # Launch Selenium Remote Control
rake rc:stop                            # Stop Selenium Remote Control running

Running the test suites individually
-------------------------------------------------------------------------------------
rake arms                               # ARMS Spec Task
rake automatic_discount                 # AUTOMATIC_DISCOUNT Spec Task
rake billing                            # BILLING Spec Task
rake central_sterile_supply             # CENTRAL_STERILE_SUPPLY Spec Task
rake fnb                                # FNB Spec Task
rake general_units                      # GENERAL_UNITS Spec Task
rake issues_for_regression              # ISSUES_FOR_REGRESSION Spec Task
rake newborn                            # NEWBORN Spec Task
rake oss                                # OSS Spec Task
rake pba_update_guarantor               # PBA_UPDATE_GUARANTOR Spec Task
rake pending_patient                    # PENDING_PATIENT Spec Task
rake pharmacy                           # PHARMACY Spec Task
rake philhealth_ordinary_case           # PHILHEALTH_ORDINARY_CASE Spec Task
rake pos                                # POS Spec Task
rake smoke_test                         # SMOKE_TEST Spec Task
rake special_units                      # SPECIAL_UNITS Spec Task
rake spu_er                             # SPU_ER Spec Task

Running the test suites sequentially
-----------------------------------------------------------------------------------
rake run_all_spec                       # Run all spec files

*********************** Running tests on Selenium Grid ***********************

Rake tasks to manage a Selenium Grid on a *single* machine.
------------------------------------------------------------------------------------

rake all:restart                        # Restart all  services (Hub and Remote Controls)
rake all:start                          # Launch all  services (Hub and Remote Controls)
rake all:stop                           # Stop all  services (Hub and Remote Controls)
rake hub:start                          # Launch Hub
rake hub:stop                           # Stop Hub
rake grid:rc:start PORT=6666            # Start a single Remote Control on port 6666
rake grid:rc:stop PORT=6666             # Stop a single Remote Control on port 6666


Running tests suites on a grid
------------------------------------------------------------------------------------
rake grid:1                             # Run tests on a grid - Batch 1
rake grid:2                             # Run tests on a grid - Batch 2
rake grid:3                             # Run tests on a grid - Batch 3
rake grid:4                             # Run tests on a grid - Batch 4
rake grid:5                             # Run tests on a grid - Batch 5
rake grid:6                             # Run tests on a grid - Batch 6
rake grid:7                             # Run tests on a grid - Batch 7
rake grid:8                             # Run tests on a grid - Batch 8
rake grid:9                             # Run tests on a grid - Batch 9
rake grid:10                            # Run tests on a grid - Batch 10
rake grid:11                            # Run tests on a grid - Batch 11
rake grid:12                            # Run tests on a grid - Batch 12
rake grid:13                            # Run tests on a grid - Batch 13
  EOS
end

#require 'win32ole'
###pck_name = "program"
###pck_version = "0.1"
CONFIG = YAML.load_file 'config.yml'

Selenium::Rake::RemoteControlStartTask.new(:'rc:start') do |rc|
  rc.port = 4444
  rc.timeout_in_seconds =  4 * 60
  rc.background = true
  rc.wait_until_up_and_running = true
  rc.jar_file = CONFIG['selenium_server_jar']
  rc.additional_args << "-firefoxProfileTemplate #{CONFIG['firefox_profile']}" if CONFIG['firefox_profile']
end

Selenium::Rake::RemoteControlStopTask.new(:'rc:stop') do |rc|
  rc.host = "localhost"
  rc.port = 4444
  rc.timeout_in_seconds = 4 * 60
end

desc "Restart Selenium Remote Control"
task :'rc:restart' do
  Rake::Task[:'rc:stop'].execute [] rescue nil
  Rake::Task[:'rc:start'].execute []
end

desc "Deletes the 'target' directory"
task :'clean' do
  FileUtils.rm_rf('target') if File.directory?('target')
end

desc "Run all spec files"
time = Time.new.strftime("%Y%m%d%a%H%M")
Spec::Rake::SpecTask.new('run_all_spec') do |t|  
  t.libs << "spec"
  t.pattern = "spec/*_spec.rb"
  t.spec_opts << "--color"
  t.spec_opts << "--require 'rubygems,selenium/rspec/reporting/selenium_test_report_formatter'"
  t.spec_opts << "--format=Selenium::RSpec::SeleniumTestReportFormatter:./target/SLMC_ALL_SPEC#{time.upcase}.html"
  t.spec_opts << "--format=specdoc"
  t.verbose = true
end

desc "my run"
time = Time.new.strftime("%Y%m%d%a%H%M")
Spec::Rake::SpecTask.new('my_run') do |t|
  t.libs << "spec"
  t.pattern = "myrun/*_spec.rb"
  t.spec_opts << "--color"
  t.spec_opts << "--require 'rubygems,selenium/rspec/reporting/selenium_test_report_formatter'"
  t.spec_opts << "--format=Selenium::RSpec::SeleniumTestReportFormatter:./target/SLMC_ALL_SPEC#{time.upcase}.html"
  t.spec_opts << "--format=specdoc"
  t.verbose = true
end


### spec =  Ruby2Jar::Rake::JarTask.new do |jar|
###    jar.files = FileList["lib/**/*", "bin/*"]
###    jar.main = "bin/program"
###    jar.name = pck_name
###    jar.version = pck_version
###    jar.add_dependency "additional_account_class2_spec.rb"
###end

##Rake::GemPackageTask.new(spec) do |pkg|
##  pkg.gem_spec = spec
##end

def new_selenium_spec_task(spec_name, spec_file)
  time = Time.new.strftime("%Y%m%d%a%H%M")
  desc "#{spec_name.upcase} Spec Task"
  Spec::Rake::SpecTask.new(:"#{spec_name}") do |t|
    t.libs << "spec"
    t.pattern = "spec/#{spec_file}"
    t.spec_opts << "--color"
    t.spec_opts << "--require 'rubygems,selenium/rspec/reporting/selenium_test_report_formatter'"
    t.spec_opts << "--format=Selenium::RSpec::SeleniumTestReportFormatter:./target/SLMC_#{spec_name.upcase}_#{time.upcase}.html"
    t.spec_opts << "--format=specdoc"
    t.verbose = true
  end
end

wd = Dir.pwd
Dir.chdir(wd + '/spec')

def create_spec_tasks
  spec_files =  Dir.glob("*_spec.rb")
  spec_names = []
  spec_files.length.times do |x|
    spec_names << spec_files[x].split('_spec.rb')
  end
  spec_names.flatten!
  spec_names.length.times do |x|
    new_selenium_spec_task("#{spec_names[x]}","#{spec_files[x]}")
  end
end

create_spec_tasks
#new_selenium_spec_task("ss","go.rb")
Dir.chdir(wd)

### Creating selenium grid batch ###

desc "Run tests on a grid - Batch 1"

#m = Dir.glob("b1*_spec.rb")
batch1 = [
  "special_units_spec.rb",
  "smoke_test_spec.rb",
  "philhealth_ordinary_case_spec.rb",
  "package_spec.rb"
]
a1 = []
batch1.length.times do |x|
  a1 << batch1[x].split('_spec.rb')
end
a1.flatten!

task :'grid:1' do
  a1.each do |x|
    res = `gnome-terminal --title=#{x} -e 'rake #{x}' &`
    abort_if_system_error res
  end
end

desc "Run tests on a grid - Batch 2"

#m = Dir.glob("b2*_spec.rb")
batch2 = [
  "search_parameter_spec.rb",
  "automatic_discount_spec.rb",
  "central_sterile_supply_spec.rb",
  "oss_spec.rb"
]
a2 = []
batch2.length.times do |x|
  a2 << batch2[x].split('_spec.rb')
end
a2.flatten!

task :'grid:2' do
  a2.each do |x|
    res = `gnome-terminal --title=#{x} -e 'rake #{x}' &`
    abort_if_system_error res
  end
end

desc "Run tests on a grid - Batch 3"

#m = Dir.glob("b3*_spec.rb")
batch3 = [
  "clinical_discharge_spec.rb",
  "pba_update_guarantor_spec.rb",
  "newborn_spec.rb",
  "or_philhealth_special_case_spec.rb",
  "pos_spec.rb"
]
a3 = []
batch3.length.times do |x|
  a3 << batch3[x].split('_spec.rb')
end
a3.flatten!

task :'grid:3' do
  a3.each do |x|
    res = `gnome-terminal --title=#{x} -e 'rake #{x}' &`
    abort_if_system_error res
  end
end

desc "Run tests on a grid - Batch 4"

#m = Dir.glob("b4*_spec.rb")
batch4 = [
  "admission_patient_registration_spec.rb",
  "fnb_spec.rb",
  "general_units_spec.rb",
  "or_spec.rb",
  "or2_spec.rb"
]
a4 = []
batch4.length.times do |x|
  a4 << batch4[x].split('_spec.rb')
end
a4.flatten!

task :'grid:4' do
  a4.each do |x|
    res = `gnome-terminal --title=#{x} -e 'rake #{x}' &`
    abort_if_system_error res
  end
end

desc "Run tests on a grid - Batch 5"

#m = Dir.glob("b5*_spec.rb")
batch5 = [
  "or_philhealth_ordinary_case_spec.rb",
  "or_philhealth_ordinary_case2_spec.rb",
  "oss_philhealth_ordinary_case_spec.rb",
  "oss_philhealth_intensive_case_spec.rb"
]
a5 = []
batch5.length.times do |x|
  a5 << batch5[x].split('_spec.rb')
end
a5.flatten!

task :'grid:5' do
  a5.each do |x|
    res = `gnome-terminal --title=#{x} -e 'rake #{x}' &`
    abort_if_system_error res
  end
end

desc "Run tests on a grid - Batch 6"

batch6 = [
  "oss_philhealth_normal_case_spec.rb",
  "oss_philhealth_normal_case2_spec.rb",
  "das_enhancement_spec.rb",
  "spu_er_spec.rb",
]
a6 = []
batch6.length.times do |x|
  a6 << batch6[x].split('_spec.rb')
end
a6.flatten!

task :'grid:6' do
  a6.each do |x|
    res = `gnome-terminal --title=#{x} -e 'rake #{x}' &`
    abort_if_system_error res
  end
end

desc "Run tests on a grid - Batch 7"

batch7 = [
  "discount_inpatient_spec.rb",
  "discount_adjustment_and_cancellation_spec.rb",
  "discount_outpatient_spec.rb",
  "discount_view_and_reprinting_spec.rb"
]
a7 = []
batch7.length.times do |x|
  a7 << batch7[x].split('_spec.rb')
end
a7.flatten!

task :'grid:7' do
  a7.each do |x|
    res = `gnome-terminal --title=#{x} -e 'rake #{x}' &`
    abort_if_system_error res
  end
end

desc "Run tests on a grid - Batch 8"

batch8 = [
  "oss_philhealth_special_case_spec.rb",
  "medical_records_spec.rb",
  "nsd_spec.rb",
  "endoscopic_spec.rb"
]
a8 = []
batch8.length.times do |x|
  a8 << batch8[x].split('_spec.rb')
end
a8.flatten!

task :'grid:8' do
  a8.each do |x|
    res = `gnome-terminal --title=#{x} -e 'rake #{x}' &`
    abort_if_system_error res
  end
end

desc "Run tests on a grid - Batch 9"

batch9 = [
  "inpatient_philhealth_other_scenarios_spec.rb",
  "philhealth_pf_claim_spec.rb",
  "philhealth_pf_claims2_spec.rb",
  "philhealth_radiation_oncology_spec.rb"
]
a9 = []
batch9.length.times do |x|
  a9 << batch9[x].split('_spec.rb')
end
a9.flatten!

task :'grid:9' do
  a9.each do |x|
    res = `gnome-terminal --title=#{x} -e 'rake #{x}' &`
    abort_if_system_error res
  end
end

desc "Run tests on a grid - Batch 10"

batch10 = [
  "inpatient_philhealth_data_entry_spec.rb",
  "inpatient_philhealth_confinement_spec.rb",
  "inpatient_philhealth_special_case_spec.rb",
  "inpatient_philhealth_normal_case_spec.rb",

]
a10 = []
batch10.length.times do |x|
  a10 << batch10[x].split('_spec.rb')
end
a10.flatten!

task :'grid:10' do
  a10.each do |x|
    res = `gnome-terminal --title=#{x} -e 'rake #{x}' &`
    abort_if_system_error res
  end
end

desc "Run tests on a grid - Batch 11"

batch11 = [
  "philhealth_cataract_spec.rb",
  "philhealth_radiation_oncology2_spec.rb",
  "ss_payment_and_soa_screen_spec.rb",
  "ss_automatic_discounts_spec.rb"
]
a11 = []
batch11.length.times do |x|
  a11 << batch11[x].split('_spec.rb')
end
a11.flatten!

task :'grid:11' do
  a11.each do |x|
    res = `gnome-terminal --title=#{x} -e 'rake #{x}' &`
    abort_if_system_error res
  end
end

desc "Run tests on a grid - Batch 12"

batch12 = [
  "special_ancillary_spec.rb",
  "wellness_enchancement_spec.rb",
  "ss_express_discharge_spec.rb",
  "ss_computation_spec.rb"
]
a12 = []
batch12.length.times do |x|
  a12 << batch12[x].split('_spec.rb')
end
a12.flatten!

task :'grid:12' do
  a12.each do |x|
    res = `gnome-terminal --title=#{x} -e 'rake #{x}' &`
    abort_if_system_error res
  end
end

desc "Run tests on a grid - Batch 13"

batch13 = [
  "inpatient_additional_manual_discount_spec.rb",
  "additional_account_class_spec.rb",
  "additional_account_class2_spec.rb",
  "additional_account_class3_spec.rb"
]
a13 = []
batch13.length.times do |x|
  a13 << batch13[x].split('_spec.rb')
end
a13.flatten!

task :'grid:13' do
  a13.each do |x|
    res = `gnome-terminal --title=#{x} -e 'rake #{x}' &`
    abort_if_system_error res
  end
end

desc "Run tests on a grid - Batch 14"

batch14 = [
  "partial_discount_spec.rb",
  "manual_discount_spec.rb",
  "oss_selective_discount_spec.rb",
  "oss_selective_discount2_spec.rb"
]
a14 = []
batch14.length.times do |x|
  a14 << batch14[x].split('_spec.rb')
end
a14.flatten!

task :'grid:14' do
  a14.each do |x|
    res = `gnome-terminal --title=#{x} -e 'rake #{x}' &`
    abort_if_system_error res
  end
end

desc "Run tests on a grid - Batch 15"

batch15 = [
  "partial_manual_discount_spec.rb",
  "discharge_instruction_screen_spec.rb",
  "philhealth_cancellation_spec.rb",
  "update_final_diagnosis_spec.rb"
]
a15 = []
batch15.length.times do |x|
  a15 << batch15[x].split('_spec.rb')
end
a15.flatten!

task :'grid:15' do
  a15.each do |x|
    res = `gnome-terminal --title=#{x} -e 'rake #{x}' &`
    abort_if_system_error res
  end
end

desc "Run tests on a grid - Batch 18"

batch18 = [
  "philhealth_newborn_spec.rb",
  "admission_page_enchancement_spec.rb"
]
a18 = []
batch18.length.times do |x|
  a18 << batch18[x].split('_spec.rb')
end
a18.flatten!

task :'grid:18' do
  a18.each do |x|
    res = `gnome-terminal --title=#{x} -e 'rake #{x}' &`
    abort_if_system_error res
  end
end

def abort_if_system_error(message)
  if system_error?
    puts "ERROR: #{message}"
    abort
  end
end

def system_error?
  $?.to_i != 0
end

#
# Managing Selenium Grid components
#

desc "Restart all  services (Hub a Remote Controls"
task :'all:restart' do
  Rake::Task[:'all:stop'].execute([]) rescue nil
  Rake::Task[:'all:start'].execute []
end

desc "Launch all  services (Hub a Remote Controls"
task :'all:start' do
  ENV['BACKGROUND'] = "true"
  Rake::Task[:'hub:start'].execute []
  puts "Waiting for Hub to come up..."
  hub.wait_until_up_and_running
  Rake::Task[:'rc:start_all'].execute []
end

desc "Stop all  services (Hub a Remote Controls"
task :'all:stop' do
  puts "Stopping all Selenium Grid servers..."
  Rake::Task[:'rc:stop_all'].execute []
  Rake::Task[:'hub:stop'].execute [] rescue nil
end

desc "Launch Hub"
task :'hub:start' do
  SGrid::Hub.new.start \
    :background => ("true" == ENV['BACKGROUND']),
    :log_file => File.native_path(File.dirname(__FILE__) + "/log/hub.log"),
    :pid_file => File.join(File.dirname(__FILE__), "pid", "hub.pid")
end

desc "Stop Hub"
task :'hub:stop' do
  puts "Shutting down Selenium Grid hub..."
  hub.shutdown rescue EOFError
  FileUtils.rm_f File.join(File.dirname(__FILE__), "pid", "hub.pid")
end

desc "Launch Remote Control"
task :'grid:rc:start' do
  port = ENV['PORT'] || 5555  
  remote_control(:port => port).start \
    :background => ENV['BACKGROUND'],
    :log_file => File.join(File.dirname(__FILE__), "log", "rc-#{port}.log"),
    :pid_file => File.join(File.dirname(__FILE__), "pid", "rc-#{port}.pid")
end

desc "Stop Remote Control"
task :'grid:rc:stop' do
  remote_control.shutdown rescue EOFError
  FileUtils.rm_f File.join(File.dirname(__FILE__), "pid", "rc-#{port}.pid")
end

desc "Launch Remote Control"
task :'rc:start_all' do
  ports = ENV['PORTS'] || "5000-5015"
  port_range = Range.new(*ports.split("-"))
  port_range.each do |port|
    remote_control(:port => port, :background => true).start \
      :background => true,
      :log_file => File.join(File.dirname(__FILE__), "log", "rc-#{port}.log"),
      :pid_file => File.join(File.dirname(__FILE__), "pid", "rc-#{port}.pid")
  end
end

desc"Stop Remote Controls. Usage rake rc:stop PORTS=5555-5560"
task :'rc:stop_all' do
  ports = ENV['PORTS'] || "5000-5015"
  port_range = Range.new(*ports.split("-"))
  port_range.each do |port|
    begin
      puts "Stopping Remote Control on port #{port}"
      rc = SGrid::RemoteControl.new :host => ENV['HOST'] || "localhost",      
        :port => port
      rc.shutdown
      FileUtils.rm_f File.join(File.dirname(__FILE__), "pid", "rc-#{port}.pid")
    rescue Exception => e
      STDERR.puts "Could not properly shutdown remote control #{port} : #{e}"
    end
  end
end

def config
  @config ||= YAML.load(File.read(File.dirname(__FILE__) + "/grid_configuration.yml"))
end

def hub_port
  (ENV["HUB_PORT"] || config["hub"]["port"]).to_i
end

def hub
  SGrid::Hub.new :port => hub_port
end

def remote_control(options={})
  SGrid::RemoteControl.new(
    :host => ENV['HOST'] || "localhost",
    :port => (options[:port] || ENV['PORT'] || 5555),
    :hub_url => (ENV['HUB_URL'] || "http://localhost:#{hub_port}"),
    :shutdown_command => ENV['RC_SHUTDOWN_COMMAND'])
end
